import requests
import re
import read
import json
from bs4 import BeautifulSoup

config = read.read()

contest_id = config['contest_id']
session = requests.get("https://vjudge.net/contest/" + contest_id)

raw_data = requests.get("https://vjudge.net/contest/rank/single/" + contest_id, cookies=session.cookies)

contestants = raw_data.json()['participants']

submissions = raw_data.json()['submissions']

# print(session.text)

match_list = config['college_match_rules']

id_map = {}

rank_map = {}

for account, nickname in contestants.items():
    for match_rule in match_list:
        if re.match(match_rule[0], nickname[1]):
            if match_rule[1] not in id_map:
                id_map[match_rule[1]] = []
            id_map[match_rule[1]].append([int(account), nickname])
            break

# print(soup.find('textarea').get_text())
contest_basic_info = json.loads(BeautifulSoup(session.text, features="html.parser").find('textarea').get_text())

penalty: int = contest_basic_info['penalty']
duration: int = (contest_basic_info['end'] - contest_basic_info['begin']) / 1000

if 'penalty' in config:
    if config['penalty'] >= 0:
        penalty = config['penalty']

if 'duration' in config:
    if config['duration'] >= 0:
        duration = config['duration']
# sub is a list consist of : {[account_id], [problem_id], [accepted or not], [time]}
for sub in submissions:
    if sub[3] >= duration:
        continue
    if sub[0] not in rank_map:
        rank_map[sub[0]] = {}
    if sub[1] not in rank_map[sub[0]]:
        rank_map[sub[0]][sub[1]] = [0, 0]
    if rank_map[sub[0]][sub[1]][0] == 0:
        if sub[2] == 1:
            rank_map[sub[0]][sub[1]][0] = 1
            rank_map[sub[0]][sub[1]][1] += sub[3]
        else:
            rank_map[sub[0]][sub[1]][1] += penalty

for college, teams in id_map.items():
    overall_solved = 0
    overall_penalty = 0
    print(college + ":")
    for team in teams:
        print(team[1])
        solved = 0
        tot_penalty = 0
        if team[0] in rank_map:
            for problem, stat in rank_map[team[0]].items():
                if stat[0] == 1:
                    solved += 1
                    tot_penalty += stat[1]
        print(str(solved) + " problem(s) solved. penalty: " + str(int(tot_penalty / 60)))
        overall_penalty += int(tot_penalty / 60)
        overall_solved += solved
    print(college + " solved " + str(overall_solved) + " problem(s) in total. total penalty: " + str(overall_penalty))

